<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 树形数组获取目标路径
      // data数组   tar需要获取的子元素值
      function TargetPathFn(data, tar) {
        const targetValue = tar
        let result
        for (let item of data) {
          const foundPath = findPath(item, targetValue)
          if (foundPath) {
            result = foundPath
            break
          }
        }
        return result
        // console.log(result)
        function findPath(node, targetValue, path = []) {
          if (node.value === targetValue) {
            return [...path, node.value]
          }

          if (node.children) {
            for (let child of node.children) {
              const foundPath = findPath(child, targetValue, [...path, node.value])
              if (foundPath) {
                return foundPath
              }
            }
          }

          return null
        }
      }
    </script>
  </body>
</html>
